import 'package:flutter/foundation.dart';
import 'package:hi_net/core/dio_adapter.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:hi_net/core/hi_net_adapter.dart';

import 'request/hi_base_request.dart';

class HiNet {
  HiNet._();
  static HiNet? _instance;
  static HiNet getInstance() {
    _instance ??= HiNet._();
    return _instance!;
  }

  Future fire(HiBaseRequest request) async {
    HiNetResponse? response;
    dynamic error;
    try {
      response = await send(request);
      printLog('response: $response');
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
    } catch (e) {
      // 其他异常
      error = e;
      printLog(e);
    }
    // 判空
    if (response == null) {
      printLog(error);
    }

    var result = response?.data;
    var status = response?.statusCode;
    switch (status) {
      case 200:
        return result;
      case null:
        throw HiNetError(-1, '网络访问失败', data: result);
      default:
        throw HiNetError(status ?? -1, result.toString(), data: result);
    }
  }

  Future<dynamic> send<T>(HiBaseRequest request) async {
    printLog("url: ${request.url()}");
    printLog("params: ${request.params}");
    // 使用Dio发送请求
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    debugPrint("hi_net: ${log.toString()}");
  }
}
